package com.yuanlrc.base.service.admin;

import com.yuanlrc.base.bean.PageBean;
import com.yuanlrc.base.dao.admin.LibraryDao;
import com.yuanlrc.base.entity.admin.Library;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

@Service
public class LibraryService  {
    @Autowired
   private LibraryDao libraryDao;
    /**
     * 根据书屋id查询
     * @param id
     * @return
     */
    public Library find(Long id){
     return libraryDao.find(id);
    }

    /**
     * 按照书屋名查找书屋
     * @param libraryName
     * @return
     */
    public Library findByLibraryname(String libraryName){
        return libraryDao.findByLibraryName(libraryName);
    }

    /**
     * 书屋添加/编辑操作
     * @param library
     * @return
     */
    public Library save(Library library){
        return libraryDao.save(library);
    }

    /**
     * 分页查询书屋列表
     * @param library
     * @param pageBean
     * @return
     */

    public PageBean<Library> findList(Library library, PageBean<Library> pageBean){
        ExampleMatcher withMatcher = ExampleMatcher.matching().withMatcher("libraryName", ExampleMatcher.GenericPropertyMatchers.contains());
        withMatcher = withMatcher.withIgnorePaths("id");
        Example<Library> example = Example.of(library, withMatcher);
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage()-1, pageBean.getPageSize());
        Page<Library> findAll = libraryDao.findAll(example, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }

    /**
     * 判断书屋名是否存在，添加和编辑均可判断
     * @param libraryName
     * @param id
     * @return
     */
    public boolean isExistLibraryName(String libraryName,Long id){
        Library library = libraryDao.findByLibraryName(libraryName);
        if(library != null){
            //表示书屋名存在，接下来判断是否是编辑书屋的本身
            if(library.getId().longValue() != id.longValue()){
                return true;
            }
        }
        return false;
    }

    /**
     * 按照书屋id删除
     * @param id
     */ 
    public void delete(Long id){
        libraryDao.deleteById(id);
    }

    /**
     * 返回书屋总数
     * @return
     */
    public long total(){
        return libraryDao.count();
    }
}
